package com.cloud.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import javax.annotation.Resource;

import com.cloud.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.cloud.bean.Task;
import com.cloud.netty.NettyServerSenssion;
import com.cloud.netty.message.ResponseMessage;
import com.cloud.util.DateFormatUtils;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

@Service
public class TaskService {
	private static Logger log = LoggerFactory.getLogger(TaskService.class);
	
	@Resource(name="threadPool")
	private ExecutorService executor;
	
	@Resource(name="nettySenssion")
	private NettyServerSenssion nettySenssion;
	
	public R newTask(String platform, String type, String code, String num) {
		// 批量发布新任务
		int free = nettySenssion.free();
		int count = Integer.parseInt(num);
		if(count>free) {
			return new R(1,"任务发布失败,任务数量过大",null);
		}
		ResponseMessage response = new ResponseMessage();
		response.setCommand(Integer.parseInt(code));
		response.setContent(type);
		response.setMsg("执行新任务");
		response.setTarget(num);
		TextWebSocketFrame tw = new TextWebSocketFrame(JSON.toJSONString(response));
		int i = 0;
		Iterator<Map.Entry<String, Task>> it = nettySenssion.getFreeTaskMap();
		while(it.hasNext()) {
			if(i == count) {
				break;
			}
			Map.Entry<String, Task> entry = it.next();
			String phone = entry.getKey();
			Task task = entry.getValue();
			task.setPlatform(Integer.parseInt(platform));
			task.setContent(type);
			task.setStatus(0);
			task.setTime(DateFormatUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
			task.setCode(Integer.parseInt(code));
			executor.execute(new Runnable() {
				@Override
				public void run() {
					nettySenssion.send(phone, tw);
					nettySenssion.addTask(phone, task);
				}
			});
			i = i + 1;
		}
		return new R(0,"任务发布成功",null);
	}

	public R flush() {
		Map<String,Object> map = new ConcurrentHashMap<String,Object>();
		ArrayList<Task> list = new ArrayList<Task>();
		int free = nettySenssion.free();
		int run = nettySenssion.running();
		int total = nettySenssion.total();
		map.put("total", total);
		map.put("free", free);
		map.put("run", run);
		log.info("设备在线情况: {}-{}-{}",free,run,total);
		Iterator<Map.Entry<String, Task>> it = nettySenssion.getRunningTaskMap();
		while(it.hasNext()) {
			Map.Entry<String, Task> entry = it.next();
			Task value = entry.getValue();
			list.add(value);
		}
		map.put("list", list);
		return new R(0,"任务监测...",map);
	}
}
